import axios from 'axios';
import ContentType from './consts/ContentTypeEnum';
import processHeaders from './processHeaders';

export default function request(path, method, data, config = {}) {
  let { headers = {} } = config;
  delete config.headers;
  let params = {};
  if (data) {
    if (data.body) {
      headers = data.headers || {};
      params = data.body;
    } else {
      params = data;
    }
  }

  const axiosConfig = {
    method,
    url: path,
    data: params,
    headers: processHeaders(method, headers),
    ...config,
  };

  if (axiosConfig.headers['Content-Type'] !== ContentType.JSON) {
    params.ui_random = new Date().getTime();
    axiosConfig.params = params;
    delete axiosConfig.data;
  }

  return axios(axiosConfig)
    .then((res) => {
      if (res.status === 200) {
        return res.data;
      }
    })
    .catch((error) => {
      console.log(error);
    });
}
